package com.yitianyigexiangfa.chatroom;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {

    int port = 8080;
    List<Socket> clients = new ArrayList<Socket>();

    public static void main(String[] args) {
        new Server();
    }

    public Server() {
        try {
            ServerSocket server = new ServerSocket(port);
            while (true) {
                Socket socket = server.accept();
                clients.add(socket);
                MyThread task = new MyThread(socket);
                task.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class MyThread extends Thread {
        Socket sscoket;
        String msg;

        public MyThread(Socket socket) {
            sscoket = socket;
        }

        public void run() {
            msg = "新的客户端上线";
            sendMsg();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(sscoket.getInputStream()));
                while ((msg = reader.readLine()) != null){
                    msg = "liubei shuo: " + msg;
                    sendMsg();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        void sendMsg(){
            System.out.println(msg);
            for (int i = 0; i < clients.size() ; i++) {
                try {
                    PrintWriter writer = new PrintWriter(clients.get(i).getOutputStream());
                    writer.println(msg);
                    writer.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
